package model;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.List;
import java.awt.Point;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

import resourceManager.ResourceManager;

/**
 * 
 * @author Charlie Hatcher
 * 
 */
public class ThreadClass implements Runnable {

	private ResourceManager resources = ResourceManager.getInstance();
	private Pixmap myPixmap;
	private int mySpeed;
	private Point myStartingPoint;
	private int myDx;
	private int myDy;
	private Color myColor;
	private int myThickness;
	private Model myModel;
	private BasicStroke myStroke;

	public ThreadClass(Pixmap p, int speed, Point sp, int dx, int dy, Color c,
			BasicStroke stroke, Model model) {
		myPixmap = p;
		mySpeed = speed;
		myStartingPoint = sp;
		myDx = dx;
		myDy = dy;
		myColor = c;
		myStroke = stroke;
		myModel = model;
		resources.addResourcesFromFile("thread");

	}

	@Override
	public void run() {
		Graphics2D graphic = myPixmap.getBackgroundImage().createGraphics();
		graphic.setStroke(myStroke);
		graphic.setPaint(myColor);
		Queue<Point> linesegments = getLineSegments(myStartingPoint, myDx,
				myDy, mySpeed);
		Thread sleepThread = new Thread();
		while (linesegments.size() >= 2) {
			Point temp = linesegments.poll();
			Point temp2 = linesegments.peek();
			graphic.drawLine((int) (temp.getX()), (int) (temp.getY()),
					(int) (temp2.getX()), (int) (temp2.getY()));
			myModel.getController().updatePixmap(myPixmap);
			try {
			    sleepThread.sleep(resources.getInteger("frame_rate"));
			} catch (InterruptedException e) {

				e.printStackTrace();
			}

		}

	}

	private Queue<Point> getLineSegments(Point sp, int dx, int dy, int speed) {
		Queue<Point> result = new LinkedList<Point>();
		Point currentpoint = sp;
		Point lastpoint = new Point((int) (sp.getX() + dx),
				(int) (sp.getY() + dy));
		int counter = 0;
		while (!currentpoint.equals(lastpoint) || counter > 1000) {
			result.add(currentpoint);
			currentpoint = new Point((int) (currentpoint.getX() + dx / speed),
					(int) (currentpoint.getY() + dy / speed));
			counter++;
		}

		return result;

	}

}
